from concurrent.futures import ThreadPoolExecutor
from numpy import arange
import requests
import sys
import os

sys.path.append(
    os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
)
from common.logger import logger
from database.park_location_record_table import EtcpParkTable

import threading

lock = threading.RLock()


def get_park_records(lat, lon):
    global lock

    url = "https://api-c-prod.etcp.cn/map/service/search/surrounding/parking/list/mini"

    params = {
        "distance": 3000,
        "onlinePayOnly": 0,
        "queryType": 1,
        "lat": lat,
        "lon": lon,
        "size": 100,
        "ak": "etcp",
    }

    rsp = requests.get(url, params=params)
    rspJson = rsp.json()

    if rspJson["code"] != 0:
        logger.error(f"请求失败: {rspJson['message']}")
        return

    if len(rspJson["data"]) == 0:
        return

    with lock:
        with EtcpParkTable() as table:
            for item in rspJson["data"]:
                record = {}
                record["parkid"] = item["id"]
                record["lat"] = item["lat"]
                record["lon"] = item["lon"]
                record["parkName"] = item["parkingName"]
                if not table.exist(item["id"]):
                    table.insert(record)

            table.commit()


if __name__ == "__main__":
    # 中国纬度范围: 3.86°N - 53.55°N
    # 中国经度范围: 73.66°E - 135.05°E

    lon_min = 96.07000000001146
    lon_max = 135.05

    lat_min = 3.86
    lat_max = 53.55

    lon_range = arange(lon_min, lon_max, 0.01)
    lat_range = arange(lat_min, lat_max, 0.01)

    try:
        for lon in lon_range:
            # 打印当前进度百分比，保留两位小数
            logger.info(
                f"lon: {lon}, progress: {(lon - lon_min) / (lon_max - lon_min) * 100:.2f} %"
            )
            thread_pool = ThreadPoolExecutor(max_workers=200)
            for lat in lat_range:
                thread_pool.submit(get_park_records, lat, lon)
            thread_pool.shutdown(wait=True)
    except Exception as e:
        logger.exception(e)
